package cn.islu.dao.impl;

import cn.islu.bean.Fruit;
import cn.islu.dao.FruitDao;
import cn.islu.utils.JdbcUtilsOnC3P0;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class FruitDaoImpl implements FruitDao {
    private QueryRunner queryRunner = new QueryRunner();
    private Connection connection = JdbcUtilsOnC3P0.getConnection();
    private int affectedRows = 0;


    @Override
    public List<Fruit> AllFruitsInfo() {
        String sql = "select * from fruit;";
        List<Fruit> fruits = null;
        try {
            fruits = queryRunner.query(connection, sql, new BeanListHandler<Fruit>(Fruit.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return fruits;
    }

    @Override
    public boolean AddFruit(Object[] params) {
        String sql = "insert into fruit(fruitname,fruitsort,fruitplace,fruitweight,fruitprice,fruitinfo) values(?,?,?,?,?,?);";

        try {
            affectedRows = queryRunner.update(connection, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectedRows != 0;
    }

    @Override
    public boolean DeleteFruit(int fruitId) {
        String sql = "delete from fruit where fruitid=?";
        try {
            affectedRows = queryRunner.update(connection, sql, fruitId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectedRows != 0;
    }

    @Override
    public boolean UpdateFruit(Object[] parames) {
        System.out.println(parames.toString());
        String sql = "update fruit set fruitname=?,fruitsort=?,fruitplace=?,fruitweight=?,fruitprice=?,fruitinfo=? where fruitid=?;";
        try {
            affectedRows = queryRunner.update(connection, sql, parames);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return affectedRows != 0;
    }

    @Override
    public List<Fruit> getFruitByPage(int start, int pageSize) {
        String sql = "select * from fruit limit ?, ?";
        Object[] params = {start, pageSize};
        List<Fruit> fruits = null;
        try {
            fruits = queryRunner.query(connection, sql, new BeanListHandler<>(Fruit.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return fruits;
    }

    @Override
    public List<Fruit> SearchFruit(String search) {
        String sql = "select * from fruit where fruitname = ?";
        Object[] params = {search};
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<>(Fruit.class), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
